package com.blockmeta.bbs.minemodule.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.SecurityUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.adapter.ThumbAdapter;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.PostResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.UploadPicResponse;
import com.blockmeta.bbs.businesslibrary.net.request.ForwardApiRequest;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.retrofit.api.NetApi;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发表反馈
 */
public class FeedBackFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R2.id.edit_title)
    EditText mEditTitle;
    @BindView(R2.id.edit_content)
    EditText mEditContent;
    @BindView(R2.id.rcv_pics)
    RecyclerView mRcvPics;

    private TakePhoto mTakePhoto;
    private InvokeParam invokeParam;//图片选择
    private ArrayList<String> pics = new ArrayList<>(8);
    private ThumbAdapter mAdapter;
    private StringBuilder mPicsBuilder = new StringBuilder();

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_feed_back, container, false);
    }

    @Override
    public void initView() {
        mRcvPics.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new ThumbAdapter(mContext, mRcvPics, R.layout.item_posted_pic, pics);
        mRcvPics.setAdapter(mAdapter);
    }


    @OnClick({R2.id.iv_emoji, R2.id.iv_pictures, R2.id.iv_link})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_emoji) {
        } else if (i == R.id.iv_pictures) {
            if (pics.size() == 4) {
                Toast.makeText(mContext, "最多只能选择4张图片", Toast.LENGTH_SHORT).show();
                return;
            }
            mTakePhoto = getTakePhoto();
            mTakePhoto.onPickMultiple(4 - pics.size());

        } else if (i == R.id.iv_link) {
        }
    }

    /**
     * 发表反馈
     */
    public void postTheFeed() {
        int titleLength = mEditTitle.getText().length();
        int contentLength = mEditContent.getText().length();
        if (titleLength < 5) {
            ToastUtil.show("标题不能小于5个字");
            return;
        }
        if (contentLength < 10) {
            ToastUtil.show("内容不能小于10个字");
            return;
        }
        //发帖
        if (pics.size() == 0) {
            //纯文本帖子
            post(null);
        } else {
            PostPicAndText();
        }
    }

    /**
     * 图文发帖，先上传图片
     */
    private void PostPicAndText() {
        mPicsBuilder.delete(0,mPicsBuilder.length());
        uploadPics();
    }

    private void uploadPics() {
        ProgressBarUtil.showProgress(mContext);
        List<Flowable<BaseCodeResponse<UploadPicResponse>>> flowables = new ArrayList<>(8);
        final NetApi.UpLoadPic upLoadPic = RetrofitFactory.getRetrofit().create(NetApi.UpLoadPic.class);
        for (String path : pics) {
            String uid = AccountHelper.getUid();
            String hash = SecurityUtil.MD5(SecurityUtil.MD5("fd8974FXTlc5Cy0j").substring(8) + uid);
            File file = new File(path);

            String fileName = path.substring(path.lastIndexOf("/"));
            RequestBody fileRQ = RequestBody.create(MediaType.parse(guessMimeType(fileName)),file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("Filedata",fileName,fileRQ);
            RequestBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("fid","41")
                    .addFormDataPart("uid",uid)
                    .addFormDataPart("hash",hash)
                    .addPart(part)
                    .build();

            Flowable<BaseCodeResponse<UploadPicResponse>> uploadFlowable=upLoadPic.upLoadPic(body, SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                    .subscribeOn(Schedulers.io());
            flowables.add(uploadFlowable);
        }

        Flowable.concatDelayError(Flowable.fromIterable(flowables))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<UploadPicResponse>commonResultByCode())
                .compose(((RxAppCompatActivity)mContext).<UploadPicResponse>bindToLifecycle())
                .subscribe(new CommonSubscriber<UploadPicResponse>(mContext) {
                    @Override
                    public void onNext(UploadPicResponse uploadPicResponse) {
                        if (uploadPicResponse!=null&&!TextUtils.isEmpty(uploadPicResponse.url)) {
                            mPicsBuilder.append("<p><img src=\"").append(uploadPicResponse.url).append("\"></p>");
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        post(mPicsBuilder.toString());
                    }

                    @Override
                    public void onError(Throwable t) {
                        post(mPicsBuilder.toString());
                    }
                });
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = null;
        try
        {
            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        if (contentTypeFor == null)
        {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
    private void post(String pic){
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String title = mEditTitle.getText().toString()+ "【 " + "Android " + provider.getProjectBuildInfo().version_name + " 】";
        String content = mEditContent.getText().toString() ;
        String message = TextUtils.isEmpty(pic)?content:content+pic;
        JSONObject json = new JSONObject();
        try {
            json.put("subject",title)
                    .put("fid",41)
                    .put("special",0)
                    .put("message",message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RetrofitFactory.getRetrofit().create(NetApi.Post.class)
                .posted(ForwardApiRequest.create(ForwardApiRequest.ApiKey.POST,json))
                .compose(RxUtil.<BaseCodeResponse<PostResponse>>rxSchedulerHelper())
                .compose(this.<BaseCodeResponse<PostResponse>>bindToLifecycle())
                .compose(RxUtil.<PostResponse>commonResultByCode())
                .subscribe(new CommonSubscriber<PostResponse>(mContext) {
                    @Override
                    public void onNext(PostResponse postResponse) {
                        ToastUtil.show("发帖成功");
                        mEditTitle.setText("");
                        mEditContent.setText("");
                        if (pics != null && pics.size() != 0) {
                            pics.clear();
                            mAdapter.notifyDataSetChanged();
                            mRcvPics.setVisibility(View.GONE);
                        }
                    }
                });

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (mTakePhoto == null) {
            mTakePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return mTakePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> TImages = result.getImages();
        for (TImage tImage : TImages) {
            String path = tImage.getOriginalPath();
            if (new File(path).length() > 1024000) {
                ToastUtil.show("单个图片不能大于1M");
            } else {
                pics.add(tImage.getOriginalPath());
            }
        }
        mAdapter.notifyDataSetChanged();
        if (pics.size() != 0) {
            mRcvPics.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }
}
